//
//  AppHelper.swift
//  TravelForUser
//
//  Created by Rowling on 2020/9/3.
//  Copyright © 2020 智蚂优服. All rights reserved.
//

import UIKit
import Alamofire

class AppHelper: NSObject {
    
    class func currentNav() -> UINavigationController? {
        if let vc = APPWindow?.rootViewController {
            if let tab = vc as? UITabBarController {
                let currentVc = tab.children[tab.selectedIndex]
                if let nav = currentVc as? UINavigationController {
                    return nav
                }
            } else if let nav = vc as? UINavigationController {
                return nav
            }
        }
        return nil
    }

    class func attributed(originStr:String, subString:String, attrs:[NSAttributedString.Key : Any], isback : Bool = false) -> NSMutableAttributedString {
        let op = isback ? NSString.CompareOptions.backwards : NSString.CompareOptions.caseInsensitive
        let range = (originStr as NSString).range(of: subString,options: op)
        let atr = NSMutableAttributedString(string:originStr )
        atr.addAttributes(attrs, range: range)
        return atr
    }
    
    class func attributed(originStr:String, range: NSRange, attrs:[NSAttributedString.Key : Any]) -> NSMutableAttributedString {
        if range.location + range.length > originStr.count {
            return NSMutableAttributedString(string: "")
        }
        let atr = NSMutableAttributedString(string:originStr)
        atr.addAttributes(attrs, range: range)
        return atr
    }
    
    class func attributed(attriStr : NSMutableAttributedString, subString:String, attrs:[NSAttributedString.Key : Any] , isback : Bool = false) -> NSMutableAttributedString {
        let op = isback ? NSString.CompareOptions.backwards : NSString.CompareOptions.caseInsensitive
        let range = (attriStr.string as NSString).range(of: subString,options: op)
        attriStr.addAttributes(attrs, range: range)
        return attriStr
    }
    
    class func reqeustHeader() -> ZMHTTPHeaders {
        var headers : ZMHTTPHeaders = [
                "Content-Type": "application/json;charset=UTF-8",
                "Accept": "application/json",
        ]
        if let id = ZMAppShareData.share.loginInfo?.uid {
            headers["userId"] = "\(id)"
        }
        if let token = ZMAppShareData.share.loginInfo?.token {
            headers["Authori-zation"] = "\(token)"
        }
        return headers
    }
    
    class func encode(bodyParam : Any) -> [String : Any]? {
//        if developMode == 3 {
            return bodyParam as? [String : Any]
//        }
//            do {
//              let data = try JSONSerialization.data(withJSONObject: bodyParam, options: JSONSerialization.WritingOptions.prettyPrinted)
//                let getStr = data.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
//    //            if ZMAppShareData.share.randomKey != "" {
//                    return ["object" : getStr, "sign" : "\(getStr + ZMAppShareData.share.randomKey)".zm.MD5()]
//    //            } else {
//    //                return nil
//    //            }
//            } catch {
//
//            }
//            return nil
    }
    
    //MARK:--------------------业务方法--------------------
    class func uploadImgs(imgs : [UIImage]) -> Observable<ResponseModel<String>> {
        if imgs.count == 0 {
            var r = ResponseModel<String>()
            r.code = .success
            r.data = ""
            r.message = ""
            return Observable<ResponseModel<String>>.just(r)
        }

        var array = [Observable<ResponseModel<[String : String]>>]()
        for img in imgs {
            let temp = ZMAPIManage<[String : String]>.rxSendRequest(CommonAPI.uploadImg(img))
            array.append(temp)
        }
        return Observable.combineLatest(array).flatMap { resp -> Observable<ResponseModel<String>> in
            let r = resp.filter({$0.code == .success}).compactMap({$0.data})
            if r.count == array.count {
                // 成功
                let s = r.map({ dic in
                    return JSON(dic)["url"].string
                }).compactMap({$0}).joined(separator: ",")
                print(s)
                var r = ResponseModel<String>()
                r.code = .success
                r.data = s
                return Observable<ResponseModel<String>>.just(r)
            }
            else {
                // 失败
                var r = ResponseModel<String>()
                r.code = .netBad
                r.data = ""
                r.message = "上传失败"
                return Observable<ResponseModel<String>>.just(r)
            }
        }
    }
    
    /// 将军令
    class func generalOrder(userId : String, randomKey : String, showId : String, time : Int, type : String, id : String) -> String {
        let remain = (time / 1000 / 60) % 36
        var str = "\(type)\(randomKey)\(userId)\(showId)\(id)".zm.MD5()
        for i in 0 ..< remain {
            str = "\(str)\(i)".zm.MD5()
            print(str)
        }
        return str
    }
    
    class func appVerify() -> Bool{
       return getAppVerify()
    }
    
    // 通过身份获取年龄
    class func getIdCardBirthday(idCard : String) -> Int? {
        let sub = idCard.subString(location: 6, length: 8)
        let fo = DateFormatter()
        fo.dateFormat = "YYYYMMdd"
        if let date = fo.date(from: sub) {
            let calenndar = Calendar.current
            let unit : Set<Calendar.Component> =  [Calendar.Component.year, Calendar.Component.month, Calendar.Component.day]
            let dateCom = calenndar.dateComponents(unit, from: date, to: Date())
//            print("year:\(dateCom.year), month:\(dateCom.month), day:\(dateCom.day)")
            return dateCom.year
        }
        return nil
    }
    
    
    //MARK: 生成渐变背景图
    class func gradientImage(colors : [CGColor],
                             rect : CGRect,
                             startPoint : CGPoint = CGPoint(x: 0, y: 0.5),
                             endPoint : CGPoint = CGPoint(x: 1, y: 0.5),
                             locations: [NSNumber]) -> UIImage? {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = rect
        gradientLayer.colors = colors
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.locations = locations
        
//        let gradientLayer = addlayer(colors, [0, 1], startPoint, endPoint, rect: rect)
        
        UIGraphicsBeginImageContextWithOptions(gradientLayer.frame.size, gradientLayer.isOpaque, 0)
        guard let context = UIGraphicsGetCurrentContext() else {return nil}
        gradientLayer.render(in: context)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
    
    //MARK:- 渐变色背景
    class func addlayer(_ colors: [CGColor] = [Style.mainColor.cgColor, Style.mainColor.cgColor], _ locations: [NSNumber] = [0, 1], _ startPoint: CGPoint = CGPoint(x: 0.24, y: 0.19), _ endPoint: CGPoint = CGPoint(x: 0.84, y: 0.85), rect : CGRect) -> CAGradientLayer {
        let bglayer = CAGradientLayer()
        bglayer.colors = colors
        bglayer.locations = locations
        bglayer.frame = rect
        bglayer.startPoint = startPoint
        bglayer.endPoint = endPoint
        return bglayer
    }
    
    // 混淆
    class func stringConfuse(v : [UInt32]) -> String {
        let m = UInt32.max
        var string = ""
        for i in v {
            let r = i ^ m
            if let sc = UnicodeScalar.init(r) {
                let ac = Character(sc)
                string.append(contentsOf: String(ac))
            }
        }
        return string
    }
    
    // 计算倒计时
    class func countTime(now : Double, end : Double) -> (h:Int, m:Int, s:Int) {
        let diff = end - now
        if diff < 0 {return (0,0,0)}
        let s = Int(diff) % 60
        let m = Int(diff) / 60 % 60
        let h = Int(diff) / 60 / 60
        return (h, m, s)
    }
}



func timeDayStr(timeStamp : Double) -> String {
    let date = timeStamp.zm.toDate() as NSDate
    if date.zm.isToday() {
        return "今天"
    }
    else if date.zm.isTomorrow() {
        return "明天"
    }
    else if date.zm.isAfterTomorrow(){
        return "后天"
    }
    else {
        return ""
    }
}

func timeAPmStr(timeStamp : Double) -> String {
    let date = timeStamp.zm.toDate() as NSDate
    let a = date.zm.toString(dateFormat: "HHmm")
    let b = Int(a) ?? 0
    if b > 500,b <= 800{
        return "早上"
    } else if b > 800, b <= 1200 {
        return "上午"
    } else if b > 1200 ,b <= 1400  {
        return "中午"
    } else if b > 1400 ,b <= 1800  {
        return "下午"
    } else if b > 1800 ,b <= 500  {
        return "晚上"
    }
    return ""
}

enum APIBool : String, HandyJSONEnum {
    case yes = "YES"
    case no = "NO"
}

func dealNum(_ num : Int)->String {
   if num >= 1000 {
       let temp = Double(num) / 1000
       return String(format:"%.1fK",temp)
   } else {
       return "\(num)"
   }
}

func dealNum(_ num : String)->String {
   let money = Double(num) ?? 0
   if money >= 1000 {
       let temp = money / 1000
       return String(format:"%.1fK",temp)
   } else {
       return "\(num)"
   }
}

func dealNum(_ num : Double)->String {
   if num >= 1000 {
       let temp = Double(num) / 1000
       return String(format:"%.1fK",temp)
   } else {
       return "\(num)"
   }
}

func translateNumToString(_ num : String) -> String {
    var newStr = ""
    for c in num {
        switch c {
        case "0":
            newStr.append("零")
        case "1":
            newStr.append("一")
        case "2":
            newStr.append("二")
        case "3":
            newStr.append("三")
        case "4":
            newStr.append("四")
        case "5":
            newStr.append("五")
        case "6":
            newStr.append("六")
        case "7":
            newStr.append("七")
        case "8":
            newStr.append("八")
        case "9":
            newStr.append("九")
        default:
            newStr.append(c)
        }
    }
    return newStr
}

